# -*- coding: utf-8 -*-
import random, time
import pandas
import requests
import re
from matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from sina来自新浪的外汇数据.获取 import *
import talib
# from sina来自新浪的外汇数据.展示 import show_1D

from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)


def analysis_amplitude_num(data=get_min_data_from_sina()):
    '展示每周期的震荡幅度统计图'
    e = []
    for i in data:
        e.append(i[1] - i[4])
    return {"所有的涨跌幅度": e}


def analysis_ups_and_downs_statistics(data=get_min_data_from_sina()):
    "统计跌涨的数量"
    pre = []

    def previous(num):
        pre.insert(0, num)
        if len(pre) > 3:
            pre.pop()

    continuity = 0
    up = 0
    down = 0
    a, b, c, d = 0, 0, 0, 0
    for i in data:
        if float(i[1]) - float(i[4]) > 0:  # 如果上涨
            up += 1
        elif float(i[1]) - float(i[4]) < 0:  # 如果下跌
            down += 1
        a, b, c, d = i, a, b, c
    # print('上涨数量', up, '下降数量', down)
    return {'上涨数量': up, '下降数量': down}


def analysis_continuity():
    '连涨连跌的情况'
    """思路：
    如果之前是涨现在还涨就+
    """
    up, down = 0, 0
    a = 0
    for i in get_min_data_from_sina():
        if float(i[1]) - float(i[4]) > 0 and a > 0:  # 如果上涨
            up += 1
        elif float(i[1]) - float(i[4]) < 0 and a < 0:  # 如果下跌
            down += 1
        a = float(i[1]) - float(i[4])
    # print(up, down)
    return {"连涨情况": up, "连跌情况": down}


def OpeningClosingAndHighest(data=get_min_data_from_sina()):
    """展示
    收盘与最高值的差
    开盘与最高值的差
    """
    open_differ = []
    close_differ = []
    for i in data:
        open_differ.append(float(i[1]) - float(i[3]))
        close_differ.append(float(i[4]) - float(i[3]))

    print(open_differ, close_differ)

    x_values = open_differ
    y_values = close_differ
    '''
    scatter() 
    x:横坐标 y:纵坐标 s:点的尺寸
    '''
    plt.scatter(x_values, y_values, s=50)

    # 设置图表标题并给坐标轴加上标签
    plt.title('OpeningClosingAndHighest', fontsize=24)
    plt.xlabel('open_differ', fontsize=14)
    plt.ylabel('close_differ', fontsize=14)

    # 设置刻度标记的大小
    plt.tick_params(axis='both', which='major', labelsize=14)
    plt.show()


def OpeningClosingAndlowst(data=get_min_data_from_sina()):
    """展示
    收盘与最高值的差
    开盘与最高值的差
    """
    open_differ = []
    close_differ = []
    for i in data:
        open_differ.append(float(i[1]) - float(i[2]))
        close_differ.append(float(i[4]) - float(i[2]))

    print(open_differ, close_differ)

    x_values = open_differ
    y_values = close_differ
    '''
    scatter() 
    x:横坐标 y:纵坐标 s:点的尺寸
    '''
    plt.scatter(x_values, y_values, s=50)

    # 设置图表标题并给坐标轴加上标签
    plt.title('OpeningClosingAndlowst', fontsize=24)
    plt.xlabel('open_differ', fontsize=14)
    plt.ylabel('close_differ', fontsize=14)

    # 设置刻度标记的大小
    plt.tick_params(axis='both', which='major', labelsize=14)
    plt.show()


def MACloseDiffer(data=get_min_data_from_sina()):
    '与均线的差值统计'
    Collection = []
    up, down = 0, 0
    cycle = 60

    cycle = 62
    for i in range(len(data)):
        # 上一次与均线相交的记录
        if i < 16: continue
        # print(i)
        # print(data[i - 16:i])
        close = [float(j[4]) for j in data[i - 16:i]]
        # print(close)

        MA = sum(close) / len(close)
        # 当前的MA值
        # print(MA)

        # if close < MA:
        #     print("当前值小于均线的值")
        # print()

        Collection.append(close[15] - MA)

    # print(Collection)
    # showHistogram_x(Collection)
    # up.append(float(i[1]) - float(i[2]))
    # down.append(float(i[4]) - float(i[2]))
    return Collection


def MAHighestLowestDiffer(data=get_min_data_from_sina()):
    '与均线的差值统计'
    Collection = []
    up, down = 0, 0
    cycle = 60

    cycle = 62
    for i in range(len(data)):
        # 上一次与均线相交的记录
        if i < 16: continue
        # print(i)
        # print(data[i - 16:i])
        close = [float(j[3]) for j in data[i - 16:i]]
        close.extend([float(j[2]) for j in data[i - 16:i]])
        # print(close)

        MA = sum(close) / len(close)
        # 当前的MA值
        # print(MA)

        # if close < MA:
        #     print("当前值小于均线的值")
        # print()

        Collection.append(close[15] - MA)

    # print(Collection)
    # showHistogram_x(Collection)
    # up.append(float(i[1]) - float(i[2]))
    # down.append(float(i[4]) - float(i[2]))
    return Collection


def MADiffer(data=get_min_data_from_sina()):
    """用来统计与上一次均线交叉的位置
    使用的是影线的数字"""

    Collection = []
    new_Collection = []
    # up, down = 0, 0
    cycle = 60
    # cycle = 62
    old_MA = 0
    for i in range(len(data)):
        # 上一次与均线相交的记录
        if i < cycle: continue
        # print(i)
        # print(data[i - 16:i])
        close = [float(j[3]) for j in data[i - cycle:i]]
        close.extend([float(j[2]) for j in data[i - cycle:i]])
        # print(close)
        MA = sum(close) / len(close)
        if old_MA == 0:            old_MA = MA
        if float(data[i][3]) > MA and float(data[i][2]) < MA:
            Collection.append(MA)
        else:

            Collection.append(old_MA)
            old_MA = MA
        print(old_MA)

        new_Collection.append(close[cycle - 1] - old_MA)

        # 当前的MA值
        # print(MA)

        # if close < MA:
        #     print("当前值小于均线的值")
        # print()

    #     Collection.append(close[cycle-1] - MA)
    #
    # # print(Collection)
    # showHistogram_x(new_Collection)
    # up.append(float(i[1]) - float(i[2]))
    # down.append(float(i[4]) - float(i[2]))
    return Collection


def anllysis_bollin(data=None):
    if not data: data = get_min_data_from_sina('usdcad')
    # 分析当前布林线的密度
    print('0.0分析用的')

    closed = [i[4] for i in data]
    closed = np.array(closed)  # List要转numpy.array类型

    # number of non-biased standard deviations from the mean
    # Moving average type: simple moving average here
    # upper, middle, lower = talib.BBANDS(closed, timeperiod=800, nbdevup=2, nbdevdn=2, matype=0)
    # print(upper, middle, lower)
    # # return upper, middle, lower
    # plt.plot(upper)
    # plt.plot(middle)
    # plt.plot(lower)
    # plt.grid()

    bollin_upper = []
    bollin_middle = []
    bollin_lower = []
    for i in range(2, 1400):
        upper, middle, lower = talib.BBANDS(closed[-i - 5:], timeperiod=i, nbdevup=2, nbdevdn=2, matype=0)
        bollin_upper.append(upper[-1])
        bollin_middle.append(middle[-1])
        bollin_lower.append(lower[-1])
        # print(upper[-1]) random.random()+1
    return {"布林上带": bollin_upper, "当前值": closed[-1], "布林下带": bollin_lower, '布林中值': bollin_middle}


if __name__ == '__main__':
    # 开盘    最低    最高    收盘
    # a = analysis_ups_and_downs_statistics()
    # print(a)
    #
    # a = analysis_continuity()
    # print(a)
    # a = analysis_amplitude_num()
    # print(a)
    a = anllysis_bollin()

    # show_1D(data=a["布林上带"],x=a['当前值'])

    for i in range(5):
        a = anllysis_bollin()
        print(a['当前值'])
        time.sleep(1)
